#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include <errno.h>
#include <stdbool.h>
#include <sqlite3.h>
#include "shmem.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <sys/types.h>
#include "msg_queue_peer.h"

// 宏定义补充（与msg_queue_peer.c保持一致）
#ifndef MSG_PATH
#define MSG_PATH "./msg_queues/" // 消息队列关联文件路径
#endif
#ifndef MAGIC_ID
#define MAGIC_ID 'm' // 魔术ID（需与msg_queue_peer.c一致）
#endif

#define MSG_QUEUE_NAME "stm" // STM消息队列名称
#define PORT 8081
#define BUFFER_SIZE 1024
#define MAX_STM_DEVICES 20                                             // STM最大设备数
#define STM_SHM_SIZE (sizeof(int) + MAX_STM_DEVICES * sizeof(Shm_Stm)) // STM共享内存大小

// 设备数据结构定义（严格匹配别人定义的Modbus共享内存结构）
typedef union equipment
{
    bool a;   // bool类型（1=真，0=假）
    int b;    // int类型（如人流量）
    double d; // double类型（如温度）
} Equipment;

// STM共享内存结构
typedef struct shm_stm
{
    int key;       // 设备唯一标识
    int type;      // 1=bool, 2=int, 3=double
    Equipment val; // 设备值
} Shm_Stm;

// Modbus共享内存结构（与别人定义的完全一致）
typedef struct shm_modbus
{
    int key;       // 设备唯一标识（101-106）
    int type;      // 1=bool, 2=int, 3=double
    int addr;      // Modbus地址（保留字段）
    Equipment val; // 设备值
} Shm_Modbus;

// 消息结构体（STM指令）
typedef struct message
{
    long mtype;      // 消息类型（必须>0）
    char mtext[256]; // 指令内容
} Message;

// 全局IPC资源变量（STM和Modbus共享内存）
struct shm_param shm_stm;     // STM共享内存参数（使用shmem.h中的结构）
void *shm_stm_addr = NULL;    // STM共享内存地址
int shm_modbus_id = -1;       // Modbus共享内存ID（别人定义的）
void *shm_modbus_addr = NULL; // Modbus共享内存地址


// 初始化IPC资源（重点：正确连接到别人定义的Modbus共享内存）
void init_ipc()
{
    // 1. 初始化STM32共享内存（使用shmem.h中的接口）
    if (shm_init(&shm_stm, "stm", STM_SHM_SIZE) < 0)
    {
        fprintf(stderr, "STM32共享内存初始化失败\n");
        exit(EXIT_FAILURE);
    }
    shm_stm_addr = shm_getaddr(&shm_stm);
    if (shm_stm_addr == NULL)
    {
        fprintf(stderr, "获取STM32共享内存地址失败\n");
        exit(EXIT_FAILURE);
    }
    printf("STM共享内存初始化成功\n");

    // 2. 连接到别人定义好的Modbus共享内存（关键修改）
    // 注意：需要替换为实际的key值（别人定义的Modbus共享内存key）
    key_t modbus_key = ftok("/tmp/ipc/shmem/modbus", 'j'); // 与别人定义的key一致
    if (modbus_key == -1)
    {
        perror("Modbus共享内存key生成失败（确认路径正确）");
        exit(EXIT_FAILURE);
    }

    // 连接到已存在的共享内存（不创建，避免覆盖别人的数据）
    // 共享内存大小：使用别人定义的实际大小（假设为1024字节，需确认）
    size_t modbus_shm_size = 1024;                             // 必须与别人定义的大小一致
    shm_modbus_id = shmget(modbus_key, modbus_shm_size, 0666); // 0666是访问权限
    if (shm_modbus_id == -1)
    {
        perror("Modbus共享内存获取失败（确认已创建）");
        exit(EXIT_FAILURE);
    }

    // 附加共享内存到当前进程地址空间
    shm_modbus_addr = shmat(shm_modbus_id, NULL, 0);
    if (shm_modbus_addr == (void *)-1)
    {
        perror("Modbus共享内存附加失败");
        exit(EXIT_FAILURE);
    }
    printf("Modbus共享内存连接成功（ID: %d）\n", shm_modbus_id);
}

// 清理IPC资源
void cleanup_ipc()
{
    // 清理STM共享内存（使用shmem.h中的接口）
    shm_del(&shm_stm);
    shm_stm_addr = NULL;

    // 清理Modbus共享内存（仅分离，不删除别人的共享内存）
    if (shm_modbus_addr != NULL)
    {
        shmdt(shm_modbus_addr);
        shm_modbus_addr = NULL;
        printf("Modbus共享内存已分离\n");
    }
}

// 获取STM设备数量
int get_stm_device_count()
{
    if (shm_stm_addr == NULL)
        return 0;
    int *count = (int *)shm_stm_addr;
    return (*count > MAX_STM_DEVICES) ? MAX_STM_DEVICES : *count;
}

// 通过key获取STM设备信息
Shm_Stm *get_stm_device_by_key(int key)
{
    if (shm_stm_addr == NULL)
    {
        fprintf(stderr, "STM共享内存未初始化\n");
        return NULL;
    }
    int *count = (int *)shm_stm_addr;
    Shm_Stm *devices = (Shm_Stm *)(count + 1); // 设备数组紧跟在数量后
    for (int i = 0; i < *count && i < MAX_STM_DEVICES; i++)
    {
        if (devices[i].key == key)
        {
            return &devices[i];
        }
    }
    return NULL; // 未找到对应key的设备
}

// 发送HTTP响应（确保格式正确）
void send_http_response(int client_socket, int status_code, const char *status_msg,
                        const char *content_type, const char *body)
{
    char headers[512];
    int length = snprintf(headers, sizeof(headers),
                          "HTTP/1.1 %d %s\r\n"
                          "Content-Type: %s\r\n"
                          "Access-Control-Allow-Origin: *\r\n"
                          "Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n"
                          "Access-Control-Allow-Headers: Content-Type\r\n"
                          "Content-Length: %zu\r\n"
                          "Connection: close\r\n"
                          "\r\n",
                          status_code, status_msg, content_type, strlen(body));
    write(client_socket, headers, length);
    write(client_socket, body, strlen(body));
}

// 处理STM数据请求
void handle_stm_data_request(int client_socket)
{
    char json_body[4096] = {0};
    char *ptr = json_body;
    int remaining = sizeof(json_body);

    // 构造JSON起始部分
    int written = snprintf(ptr, remaining, "{\"devices\":{");
    ptr += written;
    remaining -= written;

    // 获取STM设备数据（按key映射）
    Shm_Stm *temperature = get_stm_device_by_key(1); // 温度（double）
    Shm_Stm *humidity = get_stm_device_by_key(2);    // 湿度（double）
    Shm_Stm *red_light = get_stm_device_by_key(3);   // 红色LED（int）
    Shm_Stm *fire = get_stm_device_by_key(4);        // 火焰传感器（int）
    Shm_Stm *fan = get_stm_device_by_key(5);         // 风扇（int）
    Shm_Stm *window = get_stm_device_by_key(6);      // 窗户（int）
    Shm_Stm *light = get_stm_device_by_key(7);       // 灯光（int）
    Shm_Stm *buzzer = get_stm_device_by_key(8);      // 蜂鸣器（int）

    // 温度（处理NULL和类型不匹配）
    if (temperature && temperature->type == 3)
        written = snprintf(ptr, remaining, "\"temperature\":%.2f", temperature->val.d);
    else
        written = snprintf(ptr, remaining, "\"temperature\":-1");
    ptr += written;
    remaining -= written;

    // 湿度（处理NULL和类型不匹配）
    if (humidity && humidity->type == 3)
        written = snprintf(ptr, remaining, ",\"humidity\":%.2f", humidity->val.d);
    else
        written = snprintf(ptr, remaining, ",\"humidity\":-1");
    ptr += written;
    remaining -= written;

    // 红色LED（处理NULL和类型不匹配）
    if (red_light && red_light->type == 2)
        written = snprintf(ptr, remaining, ",\"red_light\":%d", red_light->val.b);
    else
        written = snprintf(ptr, remaining, ",\"red_light\":-1");
    ptr += written;
    remaining -= written;

    // 火焰传感器（处理NULL和类型不匹配）
    if (fire && fire->type == 2)
        written = snprintf(ptr, remaining, ",\"fire\":%d", fire->val.b);
    else
        written = snprintf(ptr, remaining, ",\"fire\":-1");
    ptr += written;
    remaining -= written;

    // 风扇（处理NULL和类型不匹配）
    if (fan && fan->type == 2)
        written = snprintf(ptr, remaining, ",\"fan\":%d", fan->val.b);
    else
        written = snprintf(ptr, remaining, ",\"fan\":-1");
    ptr += written;
    remaining -= written;

    // 窗户（处理NULL和类型不匹配）
    if (window && window->type == 2)
        written = snprintf(ptr, remaining, ",\"window\":%d", window->val.b);
    else
        written = snprintf(ptr, remaining, ",\"window\":-1");
    ptr += written;
    remaining -= written;

    // 灯光（处理NULL和类型不匹配）
    if (light && light->type == 2)
        written = snprintf(ptr, remaining, ",\"light\":%d", light->val.b);
    else
        written = snprintf(ptr, remaining, ",\"light\":-1");
    ptr += written;
    remaining -= written;

    // 蜂鸣器（处理NULL和类型不匹配）
    if (buzzer && buzzer->type == 2)
        written = snprintf(ptr, remaining, ",\"buzzer\":%d", buzzer->val.b);
    else
        written = snprintf(ptr, remaining, ",\"buzzer\":-1");
    ptr += written;
    remaining -= written;

    // 完成JSON
    snprintf(ptr, remaining, "}}");
    send_http_response(client_socket, 200, "OK", "application/json", json_body);
}

// 处理Modbus数据请求（从别人定义的共享内存读取数据）
// 处理Modbus数据请求（从别人定义的共享内存读取数据）
void handle_modbus_data_request(int client_socket)
{
    char json_body[4096] = {0};
    char *ptr = json_body;
    int remaining = sizeof(json_body);
    int written; // 添加缺失的变量定义

    // 检查Modbus共享内存是否连接成功
    if (shm_modbus_addr == NULL)
    {
        snprintf(json_body, sizeof(json_body), "{\"error\":\"Modbus共享内存未连接\"}");
        send_http_response(client_socket, 500, "Internal Error", "application/json", json_body);
        return;
    }

    // 共享内存结构：首地址是设备数量，后面紧跟设备数组（与Modbus代码完全一致）
    int *count_ptr = (int *)shm_modbus_addr;             // 设备数量（Modbus代码中是6）
    Shm_Modbus *devices = (Shm_Modbus *)(count_ptr + 1); // 设备数组

    // 初始化默认值（-1表示未获取到数据）
    int people_flow = -1;   // 人流量（key=101，int类型）
    double air_temp = -1.0; // 空调温度（key=105，double类型）
    int door_state = -1;    // 门状态（key=102，bool类型）
    int window_state = -1;  // 窗户状态（key=103，bool类型）
    int ac_state = -1;      // 空调状态（key=104，bool类型）
    int fan_state = -1;     // 风扇状态（key=106，bool类型）

    // 遍历共享内存设备（严格按Modbus代码中的6个设备处理）
    if (count_ptr != NULL && *count_ptr > 0)
    {
        for (int i = 0; i < *count_ptr; i++) // 遍历所有设备（count=6）
        {
            // 根据key和type提取数据（严格匹配Modbus代码的定义）
            switch (devices[i].key)
            {
            case 101:                     // 人流量（key=101，int类型）
                if (devices[i].type == 2) // type=2表示int
                    people_flow = devices[i].val.b;
                break;
            case 102:                                      // 门状态（key=102，bool类型）
                if (devices[i].type == 1)                  // type=1表示bool
                    door_state = devices[i].val.a ? 1 : 0; // bool转0/1
                break;
            case 103: // 窗户状态（key=103，bool类型）
                if (devices[i].type == 1)
                    window_state = devices[i].val.a ? 1 : 0;
                break;
            case 104: // 空调状态（key=104，bool类型）
                if (devices[i].type == 1)
                    ac_state = devices[i].val.a ? 1 : 0;
                break;
            case 105:                     // 空调温度（key=105，double类型）
                if (devices[i].type == 3) // type=3表示double
                    air_temp = devices[i].val.d;
                break;
            case 106: // 风扇状态（key=106，bool类型）
                if (devices[i].type == 1)
                    fan_state = devices[i].val.a ? 1 : 0;
                break;
            default:
                break; // 忽略其他key
            }
        }
    }
    printf("后端读取到的Modbus数据：\n");
    printf("人流量(key=101)：%d\n", people_flow);
    printf("空调温度(key=105)：%.1f\n", air_temp);
    printf("门状态(key=102)：%d\n", door_state);
    printf("窗户状态(key=103)：%d\n", window_state);
    printf("空调状态(key=104)：%d\n", ac_state);
    printf("风扇状态(key=106)：%d\n", fan_state);
    // 构造JSON响应（确保字段与前端对应）
    written = snprintf(ptr, remaining, "{");
    ptr += written;
    remaining -= written;

    // 传感器数据
    written = snprintf(ptr, remaining, "\"people_flow\":%d,", people_flow);
    ptr += written;
    remaining -= written;

    written = snprintf(ptr, remaining, "\"air_temp\":%.1f,", air_temp);
    ptr += written;
    remaining -= written;

    // 设备状态
    written = snprintf(ptr, remaining, "\"door\":%d,", door_state);
    ptr += written;
    remaining -= written;

    written = snprintf(ptr, remaining, "\"window\":%d,", window_state);
    ptr += written;
    remaining -= written;

    written = snprintf(ptr, remaining, "\"ac\":%d,", ac_state);
    ptr += written;
    remaining -= written;

    written = snprintf(ptr, remaining, "\"fan\":%d", fan_state);
    ptr += written;
    remaining -= written;

    snprintf(ptr, remaining, "}");

    // 发送响应
    send_http_response(client_socket, 200, "OK", "application/json", json_body);
}

// 处理Modbus控制请求（发送消息到Modbus程序）
void handle_modbus_control_request(int client_socket, const char *device, int state)
{
    // 验证设备和状态合法性
    if ((strcmp(device, "door") != 0 && strcmp(device, "window") != 0 &&
         strcmp(device, "ac") != 0 && strcmp(device, "fan") != 0) ||
        (state != 0 && state != 1))
    {
        send_http_response(client_socket, 400, "Bad Request",
                           "application/json", "{\"success\":false,\"message\":\"无效的设备或状态（状态必须为0或1）\"}");
        return;
    }

    // 根据设备和状态生成Modbus程序期望的命令字符串
    const char *command = NULL;
    if (strcmp(device, "door") == 0)
    {
        command = (state == 1) ? "DOOR_ON" : "DOOR_OFF";
    }
    else if (strcmp(device, "window") == 0)
    {
        command = (state == 1) ? "WINDOW_ON" : "WINDOW_OFF";
    }
    else if (strcmp(device, "ac") == 0)
    {
        command = (state == 1) ? "AIR_SWITCH_ON" : "AIR_SWITCH_OFF";
    }
    else if (strcmp(device, "fan") == 0)
    {
        command = (state == 1) ? "FAN_ON" : "FAN_OFF";
    }

    // 构造符合Modbus程序要求的消息结构体
    Message msg;                                        // 使用已定义的Message结构体（包含mtype和mtext）
    msg.mtype = 1;                                      // 消息类型必须为1（与Modbus程序接收类型一致）
    strncpy(msg.mtext, command, sizeof(msg.mtext) - 1); // 复制命令字符串
    msg.mtext[sizeof(msg.mtext) - 1] = '\0';            // 确保字符串结束

    // 发送消息到Modbus消息队列（使用msg_queue_peer.h中的接口，与Modbus程序保持一致）
    if (msg_queue_send("modbus", &msg, sizeof(msg), 0) == -1)
    {
        perror("Modbus消息发送失败");
        send_http_response(client_socket, 500, "Internal Error",
                           "application/json", "{\"success\":false,\"message\":\"消息发送失败\"}");
        return;
    }

    // 发送成功响应
    send_http_response(client_socket, 200, "OK",
                       "application/json", "{\"success\":true,\"message\":\"Modbus控制命令已发送\"}");
}

// 处理STM32控制请求
void handle_stm_control_request(int client_socket, const char *command)
{
    // 验证命令合法性
    const char *valid_commands[] = {
        "FAN_ON", "FAN_OFF", "LD1_ON", "LD1_OFF",
        "LD3_ON", "LD3_OFF", "BEEP_ON", "BEEP_OFF",
        "MOTOR_ON", "MOTOR_OFF", NULL};
    bool valid = false;
    for (int i = 0; valid_commands[i] != NULL; i++)
    {
        if (strcmp(command, valid_commands[i]) == 0)
        {
            valid = true;
            break;
        }
    }
    if (!valid)
    {
        send_http_response(client_socket, 400, "Bad Request",
                           "application/json", "{\"success\":false,\"message\":\"无效的STM命令\"}");
        return;
    }

    // 构造STM消息
    Message msg;
    msg.mtype = 1; // 消息类型
    strncpy(msg.mtext, command, sizeof(msg.mtext) - 1);
    msg.mtext[sizeof(msg.mtext) - 1] = '\0'; // 确保字符串结束

    // 发送消息到STM消息队列
    if (msg_queue_send(MSG_QUEUE_NAME, &msg, sizeof(msg), 0) == -1)
    {
        perror("STM消息发送失败");
        send_http_response(client_socket, 500, "Internal Error",
                           "application/json", "{\"success\":false,\"message\":\"STM命令发送失败\"}");
        return;
    }

    send_http_response(client_socket, 200, "OK",
                       "application/json", "{\"success\":true,\"message\":\"STM控制命令已发送\"}");
}

// 处理OPTIONS请求（跨域预检）
void handle_options_request(int client_socket)
{
    send_http_response(client_socket, 204, "No Content", "text/plain", "");
}

// 处理404
void handle_not_found(int client_socket)
{
    send_http_response(client_socket, 404, "Not Found", "text/plain", "404 - 资源未找到");
}

// 处理400
void handle_bad_request(int client_socket)
{
    send_http_response(client_socket, 400, "Bad Request", "text/plain", "400 - 无效的请求格式");
}

// 解析JSON请求体（提取command/device/state）
void parse_json_body(const char *body, char *command, char *device, int *state)
{
    // 初始化输出
    *command = '\0';
    *device = '\0';
    *state = 0;
    if (!body)
        return;

    // 提取command字段（格式："command":"XXX"）
    const char *cmd_key = strstr(body, "\"command\"");
    if (cmd_key)
    {
        const char *colon = strchr(cmd_key, ':');
        if (colon)
        {
            colon++; // 跳过冒号
            while (*colon == ' ' || *colon == '\t' || *colon == '\r' || *colon == '\n')
                colon++; // 跳过空格
            if (*colon == '"')
            {
                colon++;                                  // 跳过引号
                const char *cmd_end = strchr(colon, '"'); // 找到结束引号
                if (cmd_end && cmd_end > colon)
                {
                    int len = cmd_end - colon;
                    if (len < 32) // 限制最大长度
                    {
                        strncpy(command, colon, len);
                        command[len] = '\0';
                    }
                }
            }
        }
    }

    // 提取device字段（格式："device":"XXX"）
    const char *dev_key = strstr(body, "\"device\"");
    if (dev_key)
    {
        const char *colon = strchr(dev_key, ':');
        if (colon)
        {
            colon++; // 跳过冒号
            while (*colon == ' ' || *colon == '\t')
                colon++; // 跳过空格
            if (*colon == '"')
            {
                colon++;                                  // 跳过引号
                const char *dev_end = strchr(colon, '"'); // 找到结束引号
                if (dev_end && dev_end > colon)
                {
                    int len = dev_end - colon;
                    if (len < 32)
                    {
                        strncpy(device, colon, len);
                        device[len] = '\0';
                    }
                }
            }
        }
    }

    // 提取state字段（格式："state":0或1）
    const char *state_key = strstr(body, "\"state\"");
    if (state_key)
    {
        const char *colon = strchr(state_key, ':');
        if (colon)
        {
            colon++; // 跳过冒号
            while (*colon == ' ' || *colon == '\t')
                colon++;          // 跳过空格
            *state = atoi(colon); // 转换为整数
        }
    }
}

// 处理请求
void handle_request(int client_socket, const char *method, const char *path, const char *body)
{
    // 处理跨域预检
    if (strcmp(method, "OPTIONS") == 0)
    {
        handle_options_request(client_socket);
        return;
    }
    printf("收到请求：method=%s, path=%s\n", method, path);
    // 处理GET请求（数据获取）
    if (strcmp(method, "GET") == 0)
    {
        if (strcmp(path, "/stm/data") == 0)
        {
            handle_stm_data_request(client_socket);
            return;
        }
        else if (strcmp(path, "/modbus/data") == 0)
        {
            printf("匹配到/modbus/data，准备处理\n");
            handle_modbus_data_request(client_socket);
            return;
        }
        handle_not_found(client_socket);
        return;
    }

    // 处理POST请求（控制命令）
    if (strcmp(method, "POST") == 0)
    {
        if (strcmp(path, "/stm/control") == 0)
        {
            char command[32] = {0};
            char device[32] = {0};
            int state = 0;

            parse_json_body(body, command, device, &state);
            if (strlen(command) > 0)
            {
                handle_stm_control_request(client_socket, command);
                return;
            }
            else
            {
                handle_bad_request(client_socket);
                return;
            }
        }
        else if (strcmp(path, "/modbus/control") == 0)
        {
            char command[32] = {0};
            char device[32] = {0};
            int state = 0;
            parse_json_body(body, command, device, &state);
            if (strlen(device) > 0)
            {
                handle_modbus_control_request(client_socket, device, state);
                return;
            }
            else
            {
                handle_bad_request(client_socket);
                return;
            }
        }
        handle_bad_request(client_socket);
        return;
    }

    // 其他方法
    handle_bad_request(client_socket);
}

// 解析HTTP请求（提取method、path、body）
int parse_request(const char *buffer, char *method, char *path, char *body)
{
    if (sscanf(buffer, "%s %s", method, path) != 2)
    {
        return -1; // 解析失败
    }

    // 提取请求体（在\r\n\r\n之后）
    const char *body_start = strstr(buffer, "\r\n\r\n");
    if (body_start)
    {
        body_start += 4; // 跳过\r\n\r\n
        strncpy(body, body_start, BUFFER_SIZE - 1);
        body[BUFFER_SIZE - 1] = '\0';
    }

    return 0; // 解析成功
}

int main()
{
    // 初始化IPC资源（连接STM和别人定义的Modbus共享内存）
    init_ipc();

    // 创建TCP socket
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0)
    {
        perror("socket创建失败");
        cleanup_ipc();
        exit(EXIT_FAILURE);
    }

    // 设置socket选项（允许端口复用）
    int opt = 1;
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)))
    {
        perror("setsockopt失败");
        close(server_fd);
        cleanup_ipc();
        exit(EXIT_FAILURE);
    }

    // 绑定端口
    struct sockaddr_in address = {
        .sin_family = AF_INET,
        .sin_addr.s_addr = INADDR_ANY,
        .sin_port = htons(PORT)};
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0)
    {
        perror("bind失败（端口可能被占用）");
        close(server_fd);
        cleanup_ipc();
        exit(EXIT_FAILURE);
    }

    // 监听端口
    if (listen(server_fd, 5) < 0)
    {
        perror("listen失败");
        close(server_fd);
        cleanup_ipc();
        exit(EXIT_FAILURE);
    }

    printf("服务器启动成功，正在端口 %d 上监听...\n", PORT);
    printf("访问地址：http://localhost:%d\n", PORT);

    // 主循环（处理客户端请求）
    while (1)
    {
        struct sockaddr_in client_addr;
        socklen_t addr_len = sizeof(client_addr);

        // 接受客户端连接
        int client_socket = accept(server_fd, (struct sockaddr *)&client_addr, &addr_len);
        if (client_socket < 0)
        {
            perror("accept失败");
            continue;
        }

        // 读取请求数据
        char buffer[BUFFER_SIZE] = {0};
        ssize_t bytes_read = read(client_socket, buffer, sizeof(buffer) - 1);
        if (bytes_read > 0)
        {
            char method[16] = {0};
            char path[256] = {0};
            char body[BUFFER_SIZE] = {0};

            // 解析请求
            if (parse_request(buffer, method, path, body) == 0)
            {
                printf("收到请求: %s %s\n", method, path);
                handle_request(client_socket, method, path, body);
            }
            else
            {
                handle_bad_request(client_socket);
            }
        }

        // 关闭客户端连接
        close(client_socket);
    }

    // 清理资源（实际不会执行，需通过信号处理）
    cleanup_ipc();
    close(server_fd);
    return 0;
}